from sqlalchemy import Column, String, Integer, Table, ForeignKey, Boolean
from sqlalchemy.orm import relationship

from app.models import BaseModel, Base

# 角色-权限关联表（多对多关系）
role_permission = Table(
    'role_permission',
    Base.metadata,
    Column('role_id', Integer, ForeignKey('roles.id'), primary_key=True),
    Column('permission_id', Integer, ForeignKey('permissions.id'), primary_key=True)
)

class Permission(BaseModel):
    """权限模型"""
    __tablename__ = "permissions"
    
    name = Column(String(100), unique=True, nullable=False, comment="权限名称")
    code = Column(String(100), unique=True, nullable=False, comment="权限编码")
    description = Column(String(200), nullable=True, comment="权限描述")
    parent_id = Column(Integer, ForeignKey("permissions.id"), nullable=True, comment="父权限ID")
    is_menu = Column(Boolean, default=False, comment="是否为菜单项")
    path = Column(String(200), nullable=True, comment="前端路由路径")
    component = Column(String(200), nullable=True, comment="前端组件路径")
    icon = Column(String(100), nullable=True, comment="图标")
    sort_order = Column(Integer, default=0, comment="排序序号")
    
    # 与Role模型建立多对多关系
    roles = relationship("Role", secondary=role_permission, back_populates="permissions")
